package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author:zimmor
 * @Date: 2021/3/16 18:53
 * @Description
 * @version: 1.0.0
 */
@Component
public class ManagerFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("经过了后台网关");
        //在网关这做第一次的权限认证
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String authorization = request.getHeader("Authorization");
        if(RequestMethod.OPTIONS.equals(request.getMethod())) {
            return null;
        }
//        if()
        if(authorization!=null && !"".equals(authorization)) {
            if(authorization.equals("admin")) {
                return null;
            }
        }
        currentContext.setSendZuulResponse(false);
        currentContext.setResponseStatusCode(401);
        currentContext.setResponseBody("权限不足");
        currentContext.getResponse().setContentType("text/html;charset=UTF-8");
        return null;
    }
}
